package com.asking.Controller;

import com.asking.domain.Collection;
import com.asking.pojo.EsQuestion;
import com.asking.service.CollectionService;
import com.asking.utils.JWTUtil;
import com.asking.vo.Result;
import com.asking.vo.ResultVo;
import com.github.pagehelper.PageInfo;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/collection")
public class CollectionController {
    @Resource
    private CollectionService collectionService;

    /**
     * 添加收藏
     *
     * @param qid
     * @param request
     */
    @PostMapping
    public void addCollection(String qid, HttpServletRequest request) {
        String token = request.getHeader("token");
        token = token.substring(7);
        String user = JWTUtil.getUser(token);
        String[] split = user.split("#");
        collectionService.addCollection(split[1], qid);
    }

    /**
     * 移除收藏
     *
     * @param qid
     * @param request
     */
    @DeleteMapping
    public void deleteCollection(String qid, HttpServletRequest request) {
        String token = request.getHeader("token");
        token = token.substring(7);
        String user = JWTUtil.getUser(token);
        String[] split = user.split("#");
        collectionService.deleteCollection(split[1], qid);
    }

    /**
     * 查询该用户收藏
     *
     * @param request
     * @return
     */
    @GetMapping
    public ResponseEntity<Result> findCollection(HttpServletRequest request) {

        try {
            String token = request.getHeader("token");
            token = token.substring(7);
            String user = JWTUtil.getUser(token);
            String[] split = user.split("#");
            PageInfo<EsQuestion> question = collectionService.findQuestion(split[1]);
            return new ResponseEntity<>(new Result(200, "收藏查询失败", new ResultVo<>(question.getPages(), question.getList())), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(new Result(500, "收藏查询失败"),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}